package com.rednote.service.impl;
import com.rednote.service.UserLikesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rednote.common.UserContextHolder;
import com.rednote.entity.Posts;
import com.rednote.entity.UserCollect;
import com.rednote.entity.Users;
import com.rednote.entity.vo.AuthorVO;
import com.rednote.entity.vo.PostCardVO;
import com.rednote.mapper.PostsMapper;
import com.rednote.mapper.UserCollectMapper;
import com.rednote.mapper.UsersMapper;
import com.rednote.service.UserCollectService;
import com.rednote.service.UserFollowService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class UserCollectServiceImpl implements UserCollectService {

    @Autowired
    private UserCollectMapper collectMapper;
    @Autowired
    private PostsMapper postMapper;
    @Resource
    private PostsMapper postsMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private UserFollowService userFollowService;

    private static final Logger log = LoggerFactory.getLogger(UserCollectServiceImpl.class);
    @Autowired
    private UserLikesService userLikesService;

    @Override
    public synchronized void collect(Integer postId) {
        if (isCollected(postId)) {
            throw new RuntimeException("帖子已收藏");
        } else {
            // 未收藏，插入
            Integer userId = UserContextHolder.getUserId();
            UserCollect collect = new UserCollect();
            collect.setUserId(userId);
            collect.setPostId(postId);
            collectMapper.insert(collect);
            //更新帖子收藏数
            postMapper.updateCollectCount(postId, 1);

        }
    }

    @Override
    public synchronized void cancelCollect(Integer postId) {
        if(isCollected(postId)) {
            Integer userId = UserContextHolder.getUserId();
            QueryWrapper<UserCollect> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId).eq("post_id", postId);
            collectMapper.delete(wrapper);
            // 更新帖子收藏数
            postMapper.updateCollectCount(postId, -1);
        } else {
            throw new RuntimeException("帖子未收藏");
        }

    }

    @Override
    public boolean isCollected(Integer postId) {
        Integer userId = UserContextHolder.getUserId();
        QueryWrapper<UserCollect> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("post_id", postId);
        Long count=collectMapper.selectCount(wrapper);
        return count != null && count > 0;
    }

    @Override
    public List<UserCollect> listUserCollects(int userId) {
        return collectMapper.selectByUserId(userId);
    }

    @Override
    public Page<PostCardVO> getCollectList(Integer page, Integer limit) {
        Integer userId = UserContextHolder.getUserId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }

        // 创建分页对象
        Page<UserCollect> collectPage = new Page<>(page, limit);

        // 构建查询条件
        LambdaQueryWrapper<UserCollect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserCollect::getUserId, userId)
                .orderByDesc(UserCollect::getCreatedAt);

        // 执行分页查询
        Page<UserCollect> result = collectMapper.selectPage(collectPage, queryWrapper);

        // 创建返回的分页对象
        Page<PostCardVO> voPage = new Page<>(page, limit, result.getTotal());
        List<PostCardVO> voList = new ArrayList<>();

        // 查询收藏的帖子信息
        for (UserCollect collect : result.getRecords()) {
            Posts post = postsMapper.selectById(collect.getPostId());
            if (post != null) {
                PostCardVO vo = new PostCardVO();
                vo.setId(post.getPostId());
                vo.setTitle(post.getTitle());
                vo.setLike(post.getLikeCount());
                vo.setIsPrivate(false);
                vo.setIsLike(userLikesService.getIsLike(post.getPostId(),0));
                vo.setIsFav(this.isCollected(post.getPostId()));
                // 处理封面图片
                try {
                    if (post.getVideoUrl() != null && !post.getVideoUrl().isEmpty()) {
                        vo.setImg(post.getCoverUrl());
                        vo.setVideo(post.getVideoUrl());
                        vo.setDuration(post.getDuration());
                        vo.setType("video");
                    } else {
                        ObjectMapper mapper = new ObjectMapper();
                        List<String> imageUrls = mapper.readValue(post.getImageUrls(),
                                new TypeReference<List<String>>() {});
                        vo.setImg(imageUrls != null && !imageUrls.isEmpty() ? imageUrls.get(0) : null);
                        vo.setType("image");
                    }
                } catch (Exception e) {
                    log.error("处理图片URL失败: postId=" + post.getPostId(), e);
                }

                // 处理标签
                if (StringUtils.hasText(post.getTag())) {
                    vo.setTags(Arrays.asList(post.getTag().split(",")));
                } else {
                    vo.setTags(Collections.emptyList());
                }

                // 设置作者信息
                Users author = usersMapper.selectById(post.getUserId());
                if (author != null) {
                    AuthorVO authorVO = new AuthorVO();
                    authorVO.setId(author.getUserId());
                    authorVO.setName(author.getUsername());
                    authorVO.setImg(author.getAvatar());
                    authorVO.setIsAuthor(Objects.equals(userId, author.getUserId()));
                    authorVO.setIsFollowed(userFollowService.isFollowed(author.getUserId()));
                    vo.setAuthor(authorVO);
                }

                voList.add(vo);
            }
        }

        voPage.setRecords(voList);
        return voPage;
    }

}
